package concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class CountExample {
    //有200个用户同时访问
    private static int threadTotal = 200;
    //系统短时间内接收到5000个请求
    private static int clientTotal = 5000;

    private static long count = 0;

    public static void main(String[] args) {
        //线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        //信号量
        final Semaphore semaphore = new Semaphore(threadTotal);

        //模拟客户端发送的5000个请求。同一时间内允许200个请求同时执行
        for(int index = 0; index < clientTotal; index++){
            exec.execute(() -> {
                try{
                    semaphore.acquire();
                    add();
                    semaphore.release();

                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }

        exec.shutdown();
        System.out.println("count: " + count);

        //1个线程和200个线程，输出的计数不一样

    }

    private static void add() {
        count++;
    }
}
